<?php
namespace Admin\Controller;
use Admin\Controller\BaseController;

class HomeworkController extends BaseController {

	public function index() {
		if(IS_POST) {
			$logicClassId = I('post.logic_class_id');
		} else {
			$logicClass = M('LogicClass')->find();
			$logicClassId = $logicClass['id'];
		}
		$homeworks = M('Homework')->where(array('logic_class_id' => $logicClassId))
			->order('start_time')
			->select();
		$this->assign('logic_class_id', $logicClassId);
		$this->assign('logic_classes', M('LogicClass')->order('id')->select());
		$this->assign('homeworks', $homeworks);
		$this->display();
	}

	public function add() {
		$this->assign('logic_classes', M('LogicClass')->select());
		$this->display();
	}

	public function addPost() {
		if(!IS_POST) {
			$this->redirect('Homework/index');
		}
		$homework = D('Homework');
		if(!$homework->create()) {
			$this->error($homework->getError());
		}
		if(!$homework->checkUnique($homework->data())) {
			$this->error('作业已存在！');
		}
		if(!$homework->add()) {
			$this->error('数据写入失败！');
		}
		$this->success('添加成功！', U('Homework/index'));
	}

	public function deletePost() {
		if(!IS_POST) {
			$this->redirect('Homework/index');
		}
		$id = I('post.id');
		// 删除作业前先删除与该作业相关的学生作业表记录
		$result = M('HomeworkStudent')->where(array('homework_id' => $id))->select();
		foreach($result as $row) {
			$filename = $row['file_savepath'] . $row['file_savename'];
			unlink($filename);
		}
		if(false === M('HomeworkStudent')->where(array('homework_id' => $id))->delete()) {
			$this->error('删除与该作业相关的学生作业表记录失败！');
		}
		if(!M('Homework')->where(array('id' => $id))->delete()) {
			$this->error('删除失败！');
		}
		$this->success('删除成功！', U('Homework/index'));
	}

	public function modify() {
		$id = I('id');
		$this->_detail($id);
		$this->display();
	}

	public function modifyPost() {
		if(!IS_POST) {
			$this->redirect('Homework/index');
		}
		$homework = D('Homework');
		if(!$homework->create()) {
			$this->error($homework->getError());
		}
		if(!$homework->checkUnique($homework->data())) {
			$this->error('作业已存在！');
		}
		// $homework->checkUnique() 中的 $result = $this->where($map)->find()
		// 如果 $homework->data() 中存在 id主键
		// $homework->data() 会被刷新为 数据库中的信息
		// 所以这里 $homework->create() 的任务是 更改 $homework->data() 的字段信息为从表单提交的信息
		if(!$homework->create()) {
			$this->error($homework->getError());
		}
		$result = $homework->save();
		if($result === false) {
			$this->error('数据更新失败！');
		}
		$this->success('修改成功！', U('Homework/index'), 0);
	}

	public function detail() {
		$id = I('id');
		$this->_detail($id);
		$this->display();
	}

	protected function _detail($id) {
		$homework = D('Homework')->where(array('id' => $id))->relation('logic_class')->find();
		$logicClasses = M('LogicClass')->order('id')->select();
		$this->assign('homework', $homework);
		$this->assign('logic_classes', $logicClasses);
	}

}
